use anyhow::Result;
use sqlx::SqlitePool;

use crate::services::{UserService, SessionService, PermissionService};
use crate::database::models::CreateUserRequest;
use shared::types::{User, Session, PermissionType};

#[derive(Clone)]
pub struct AuthManager {
    user_service: UserService,
    session_service: SessionService,
    permission_service: PermissionService,
}

impl AuthManager {
    pub fn new(pool: SqlitePool) -> Self {
        Self {
            user_service: UserService::new(pool.clone()),
            session_service: SessionService::new(pool.clone()),
            permission_service: PermissionService::new(pool),
        }
    }
    
    /// 用户登录
    pub async fn login(&self, username: &str, password: &str, client_ip: String, client_port: u16) -> Result<Session> {
        // 验证用户凭据
        let user = self.user_service.authenticate_user(username, password).await?;
        
        // 创建会话
        let session = self.session_service.create_session(
            user.id,
            client_ip,
            client_port
        ).await?;
        
        Ok(session)
    }
    
    /// 验证会话
    pub async fn validate_session(&self, token: &str) -> Result<Option<Session>> {
        self.session_service.validate_session(token).await
    }
    
    /// 用户登出
    pub async fn logout(&self, session_id: i64) -> Result<()> {
        self.session_service.delete_session(session_id).await
    }
    
    /// 检查权限
    pub async fn check_permission(&self, user_id: i64, permission: PermissionType, path: &str) -> Result<bool> {
        self.permission_service.check_permission(user_id, permission, path).await
    }
    
    /// 检查读取权限
    pub async fn can_read(&self, user_id: i64, path: &str) -> Result<bool> {
        self.permission_service.can_read(user_id, path).await
    }
    
    /// 检查写入权限
    pub async fn can_write(&self, user_id: i64, path: &str) -> Result<bool> {
        self.permission_service.can_write(user_id, path).await
    }
    
    /// 检查删除权限
    pub async fn can_delete(&self, user_id: i64, path: &str) -> Result<bool> {
        self.permission_service.can_delete(user_id, path).await
    }
    
    /// 检查管理员权限
    pub async fn is_admin(&self, user_id: i64) -> Result<bool> {
        self.permission_service.is_admin(user_id).await
    }
    
    /// 创建用户
    pub async fn create_user(&self, request: &CreateUserRequest) -> Result<User> {
        self.user_service.create_user(request).await
    }
    
    /// 获取用户信息
    pub async fn get_user(&self, user_id: i64) -> Result<Option<User>> {
        self.user_service.get_user_by_id(user_id).await
    }
    
    /// 更新会话
    pub async fn update_session(&self, session: &Session) -> Result<()> {
        self.session_service.update_session(session).await
    }
    
    /// 清理过期会话
    pub async fn cleanup_expired_sessions(&self) -> Result<u64> {
        self.session_service.cleanup_expired_sessions().await
    }
}
